<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/6/30
 * Time: 10:11
 */

namespace app\admin\service;

use \think\Image;

class Upload
{
    /**
     * 单文件上传
     */
    public static function singleUpload($file,$type = 3,$is_cut = 0){
        // 判断type选择目录
        if ($type == 1) {$type = 'image';} elseif ($type == 2) {$type = 'video';} else {$type = 'temp';}
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads'.DS.$type);
            if($info){
                // 成功上传后 获取上传信息
                $savename = '/uploads/'. $type.'/'.str_replace('\\', '/',  $info->getSaveName());
                // 判断是否需要裁减处理
                if ( $is_cut ) {
                    Upload::cutImage('.'.$savename,960,600);
                }
                // 返回信息
                $data = [
                    'savename' => $savename,
                    'filename' => $info->getFilename(),
                    'message' => 'ok'
                ];
                return $data;
            }else{
                // 上传失败获取错误信息
                return $data['message'] = 'no';
            }
        }
    }

    /**
     * 图片处理
     */
    public static function cutImage($pic_path,$width = 150,$height = 150)
    {
        $image = Image::open($pic_path);
        $image->thumb($width,$height,\think\Image::THUMB_CENTER)->save($pic_path);
    }
}